﻿using System.Collections.Generic;
using RssReader.Common;
using RssReader.DataModel;
using Windows.UI.ApplicationSettings;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.ApplicationModel.Search;
using RssReader.Feeds;
using System;

// The Grouped Items Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234231

namespace RssReader
{
    /// <summary>
    /// A page that displays a grouped collection of items.
    /// </summary>
    public sealed partial class GroupedItemsPage : LayoutAwarePage
    {
        #region Privates

        readonly Popup _popup = new Popup();
        private readonly CategoryHelper _categoryHelper = new CategoryHelper();
        static private readonly Dictionary<string, object> SessionState = new Dictionary<string, object>();
        
        //SearchPane Object
        #endregion


        public GroupedItemsPage()
        {
            this.InitializeComponent();
            
            SettingsPane.GetForCurrentView().CommandsRequested += App.SettingsCommandHelper.On_commands_requested;
            NavigationCacheMode = NavigationCacheMode.Enabled;
        }

        static public Dictionary<string, object> Session_state
        {
            get { return SessionState; }
        }

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            MainGrid.Background = new SolidColorBrush(App.ARGBColor);
            bounds.Text = Fix_item_height_for_current_screen_resolution();
            Get_feed();
        }

        /// <summary>
        /// Preserves state associated with this page in case the application is suspended or the
        /// page is discarded from the navigation cache.  Values must conform to the serialization
        /// requirements of <see cref="SuspensionManager.SessionState"/>.
        /// </summary>
        /// <param name="pageState">An empty dictionary to be populated with serializable state.</param>
        protected override void SaveState(Dictionary<String, Object> pageState)
        {
        }

        public async void Get_feed()
        {
            ring.IsActive = true;
            var categories = await _categoryHelper.Get_all_categories();

            ring.IsActive = false;
            DefaultViewModel["Categories"] = categories;
            Remove_session_value();
            SessionState.Add(App.ItemsKeyString, categories);
        }

        

        private static void Remove_session_value()
        {
            if (SessionState.ContainsKey(App.ItemsKeyString))
                SessionState.Remove(App.ItemsKeyString);
        }

        /// <summary>
        /// Invoked when an item within a group is clicked.
        /// </summary>
        /// <param name="sender">The GridView (or ListView when the application is snapped)
        /// displaying the item clicked.</param>
        /// <param name="e">Event data that describes the item clicked.</param>
        void Item_view_item_click(object sender, ItemClickEventArgs e)
        {
            var itemDetailsViewHelper = new ItemDetailsViewHelper().Get_selected_item_and_show_item_details_view(e, App.ItemsKeyString, Window.Current.Content);
            this.Frame.Navigate(typeof(ItemDetailPage), itemDetailsViewHelper);
        }

        void Header_click(object sender, RoutedEventArgs e)
        {
            var currentFrame = Window.Current.Content as Frame;
            var currentFrameType = App.Current_source_page_type(currentFrame);
            var selectedCategory = (sender as FrameworkElement).DataContext;

            var tuple = new Tuple<Category, Type>((Category) selectedCategory, currentFrameType);
            // Determine what group the Button instance represents

            // Navigate to the appropriate destination page, configuring the new page
            // by passing required information as a navigation parameter
            this.Frame.Navigate(typeof(GroupDetailPage), tuple);
        }

        private void All_items_view_click(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(ItemsPage));
        }

        private void Add_category(object sender, RoutedEventArgs e)
        {
            SearchPane.GetForCurrentView().ShowOnKeyboardInput = false;
            _popup.Child = new AddCategoryPopup(_popup,this);
            _popup.VerticalOffset = 200.0;
            _popup.HorizontalOffset = 410.0;
            _popup.IsOpen = true;
            _popup.IsLightDismissEnabled = true;
        }
    }
}
